"""
ECB没有偏移量
"""
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

g_pwd = "PWD"


def add_to_16(text):

    if isinstance(text, bytes):
        print("this is ")
        add = 16 - (len(text) % 16)
        if add == 16:
            add = 0
        return text +  (b'\0' * add)
    else:
        if len(text.encode('utf-8')) % 16:
            add = 16 - (len(text.encode('utf-8')) % 16)
        else:
            add = 0
    text = text + ('\0' * add)
    return text.encode('utf-8')


# 加密函数
def encrypt(text):
    key = g_pwd.encode('utf-8')
    mode = AES.MODE_ECB
    text = add_to_16(text)
    cryptos = AES.new(key, mode)

    cipher_text = cryptos.encrypt(text)
    return b2a_hex(cipher_text)


# 解密后，去掉补足的空格用strip() 去掉
def decrypt(text):
    key = g_pwd.encode('utf-8')
    mode = AES.MODE_ECB
    cryptor = AES.new(key, mode)
    plain_text = cryptor.decrypt(a2b_hex(text))
    return bytes.decode(plain_text).rstrip('\0')

import base64

import os
import sys

basepath = os.path.dirname(os.path.realpath(__file__))

encode_file = f"{basepath}/encoded"

print("\r\ndecoding...")
print("read aes encoded file:", encode_file)
with open(encode_file, "rb") as f:
    ectx = f.read()

print("decrypting...")
r = decrypt(ectx)
print("ctx len:", len(r))
print("b64decode...")
debs64 = base64.b64decode(r)
print("b64decode...len:", len(debs64))


decode_file = f"{basepath}/decoded.tar.gz"
decode_dir = f"{basepath}/decoded"
os.system(f"mkdir -p {decode_dir}")

print("write decoded ctx to file:", decode_file)

with open(decode_file, "wb") as f:
    f.write(debs64)

print("untar...")

os.system(f"tar -zxf {decode_file} -C {decode_dir}")




